#include "t_setparams.h"
#include "ElaTheme.h"
#include "ElaScrollPageArea.h"
#include "ElaText.h"
#include "ElaLineEdit.h"
#include "ElaComboBox.h"
#include "ElaCheckBox.h"
#include "ElaMessageBar.h"
#include "ElaPushButton.h"
#include "ElaRadioButton.h"
#include "t_excel.h"
#include "t_packinfo.h"
#include "T_PaintWidget.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QFileDialog>
#include <cmath>
#include <QGlobalStatic>
#include <QDebug>

Q_GLOBAL_STATIC(T_SetParams,s_instance)

BlockInfo g_blockInfo = {};
ResultInfo g_resultInfo = {};
double g_duan_value_H = 0.0;
double g_duan_value_V = 0.0;

T_SetParams::T_SetParams(QWidget *parent)
    : ElaScrollPage(parent)
{
    connect(eTheme, &ElaTheme::themeModeChanged, this, [=]() {
        if (!parent)
        {
            update();
        }
    });

    initArea();
    initUI();
}

T_SetParams::~T_SetParams()
{

}

T_SetParams *T_SetParams::Instance()
{
    return s_instance;
}

void T_SetParams::setAllowCreate(bool is_allow_create)
{
    m_is_allow_create = is_allow_create;
}

void T_SetParams::initUI()
{
    setFixedSize(550,600);

    QWidget* centralWidget = new QWidget(this);
    centralWidget->setWindowTitle("参数设置");
    QVBoxLayout* centerLayout = new QVBoxLayout(centralWidget);
    centerLayout->addWidget(m_blockInfoArea);
    centerLayout->addStretch();
    centerLayout->setContentsMargins(0, 0, 0, 0);
    addCentralWidget(centralWidget, true, true, 0);

    //初始化完成自动导入电芯库
    importExcel("电芯库.xlsx");
}

void T_SetParams::initArea()
{
    ElaPushButton *importExcelBtn = new ElaPushButton("导入参数表",this);
    connect(importExcelBtn,&ElaPushButton::clicked,this,&T_SetParams::on_importExcelBtnClicked);

    QHBoxLayout *hLayout_0 = new QHBoxLayout();
     hLayout_0->addStretch();
    hLayout_0->addWidget(importExcelBtn);


    //创建电芯选择行
    ElaText *text = new ElaText("产品型号",15,this);
    text->setWordWrap(false);

    m_combobox = new ElaComboBox(this);
    m_combobox->setMinimumWidth(200);
    connect(m_combobox,&ElaComboBox::currentTextChanged,this,&T_SetParams::on_currentTextChanged);    

    QHBoxLayout *hLayout_1 = new QHBoxLayout();
    hLayout_1->addWidget(text);
    hLayout_1->addStretch();
    hLayout_1->addWidget(m_combobox);

    //创建结构预设尺寸
    ElaText *totalWText = new ElaText("整体长度(mm)",15,this);
    totalWText->setWordWrap(false);
    m_totalWLe = new ElaLineEdit(this);
    m_totalWLe->setText("1600");
    connect(m_totalWLe,&ElaLineEdit::textEdited,this,[=](){
        m_is_allow_create = false;
    });

    QHBoxLayout *hLayout_2 = new QHBoxLayout();
    hLayout_2->addWidget(totalWText);
    hLayout_2->addStretch();
    hLayout_2->addWidget(m_totalWLe);

    ElaText *totalHText = new ElaText("整体宽度(mm)",15,this);
    totalHText->setWordWrap(false);
    m_totalHLe = new ElaLineEdit(this);
    m_totalHLe->setText("800");
    connect(m_totalHLe,&ElaLineEdit::textEdited,this,[=](){
        m_is_allow_create = false;
    });

    QHBoxLayout *hLayout_3 = new QHBoxLayout();
    hLayout_3->addWidget(totalHText);
    hLayout_3->addStretch();
    hLayout_3->addWidget(m_totalHLe);

    ElaText *totalHDText = new ElaText("整体厚度(mm)",15,this);
    totalHDText->setWordWrap(false);
    m_totalHDLe = new ElaLineEdit(this);
    m_totalHDLe->setText("500");
    connect(m_totalHDLe,&ElaLineEdit::textEdited,this,[=](){
        m_is_allow_create = false;
    });

    QHBoxLayout *hLayout_4 = new QHBoxLayout();
    hLayout_4->addWidget(totalHDText);
    hLayout_4->addStretch();
    hLayout_4->addWidget(m_totalHDLe);

    //创建主体结构交换长宽
    ElaText *swapText = new ElaText("交换主体长宽",15,this);
    swapText->setWordWrap(false);
    ElaCheckBox *checkBox = new ElaCheckBox("是否交换",this);
    connect(checkBox,&ElaCheckBox::clicked,this,[=](bool checked){
        m_main_is_swap = checked;
        m_is_allow_create = false;
    });
    swapText->hide();
    checkBox->hide();

    QHBoxLayout *hLayout_5 = new QHBoxLayout();
    hLayout_5->addWidget(swapText);
    hLayout_5->addStretch();
    hLayout_5->addWidget(checkBox);

    //创建额定电压、额定容量
    ElaText *blockValueText = new ElaText("额定电压(V)",15,this);
    blockValueText->setWordWrap(false);
    m_blockVolValueLe = new ElaLineEdit(this);
    connect(m_blockVolValueLe,&ElaLineEdit::editingFinished,this,&T_SetParams::on_volLeEditFinished);    

    QHBoxLayout *hLayout_6 = new QHBoxLayout();
    hLayout_6->addWidget(blockValueText);
    hLayout_6->addStretch();
    hLayout_6->addWidget(m_blockVolValueLe);

    ElaText *blockAhValueText = new ElaText("额定电量(kWh)",15,this);
    blockValueText->setWordWrap(false);
    m_blockAhValueLe = new ElaLineEdit(this);
    connect(m_blockAhValueLe,&ElaLineEdit::editingFinished,this,&T_SetParams::on_ahLeEditFinished);

    QHBoxLayout *hLayout_7 = new QHBoxLayout();
    hLayout_7->addWidget(blockAhValueText);
    hLayout_7->addStretch();
    hLayout_7->addWidget(m_blockAhValueLe);

    //创建放置方式
    ElaText *hvText = new ElaText("电芯放置方式",15,this);
    hvText->setWordWrap(false);
    m_hButton = new ElaRadioButton("水平",this);
    m_vButton = new ElaRadioButton("垂直",this);
    m_ddButton = new ElaRadioButton("堆叠",this);
    m_hvddButtonGroup = new QButtonGroup(this);
    m_hvddButtonGroup->addButton(m_hButton,0);
    m_hvddButtonGroup->addButton(m_vButton,1);
    m_hvddButtonGroup->addButton(m_ddButton,2);
    connect(m_hvddButtonGroup,QOverload<QAbstractButton*, bool>::of(&QButtonGroup::buttonToggled),this,&T_SetParams::on_hvddButtonGroupToggled);

    m_vButton->setChecked(true);
    m_hButton->hide();
    m_vButton->hide();
    m_ddButton->hide();
    hvText->hide();

    QHBoxLayout *hLayout_8 = new QHBoxLayout();
    hLayout_8->addWidget(hvText);
    hLayout_8->addStretch();
    hLayout_8->addWidget(m_hButton);
    hLayout_8->addWidget(m_vButton);
    hLayout_8->addWidget(m_ddButton);

    //创建排列方式
    ElaText *lwhText = new ElaText("电芯排列方式",15,this);
    lwhText->setWordWrap(false);
    m_lwButton = new ElaRadioButton("长宽",this);
    m_lhButton = new ElaRadioButton("长高",this);
    m_hwButton = new ElaRadioButton("高宽",this);
    m_wlButton = new ElaRadioButton("宽长",this);
    m_whButton = new ElaRadioButton("宽高",this);
    m_hlButton = new ElaRadioButton("高长",this);
    m_lwhlButtonGroup = new QButtonGroup(this);
    m_lwhlButtonGroup->addButton(m_lwButton,0);
    m_lwhlButtonGroup->addButton(m_lhButton,1);
    m_lwhlButtonGroup->addButton(m_hwButton,2);
    m_lwhlButtonGroup->addButton(m_wlButton,3);
    m_lwhlButtonGroup->addButton(m_whButton,4);
    m_lwhlButtonGroup->addButton(m_hlButton,5);
    connect(m_lwhlButtonGroup,QOverload<QAbstractButton*, bool>::of(&QButtonGroup::buttonToggled),this,&T_SetParams::on_lwhlButtonGroupToggled);

    m_lhButton->setChecked(true);
    //隐藏
    lwhText->hide();
    m_lwButton->hide();
    m_lhButton->hide();
    m_hwButton->hide();
    m_wlButton->hide();
    m_whButton->hide();
    m_hlButton->hide();

    QHBoxLayout *hLayout_9 = new QHBoxLayout();
    hLayout_9->addWidget(lwhText);
    hLayout_9->addStretch();
    hLayout_9->addWidget(m_lwButton);
    hLayout_9->addWidget(m_lhButton);
    hLayout_9->addWidget(m_hwButton);
    hLayout_9->addWidget(m_wlButton);
    hLayout_9->addWidget(m_whButton);
    hLayout_9->addWidget(m_hlButton);

    ElaText *hzjText = new ElaText("模组排列方式",15,this);
    hzjText->setWordWrap(false);
    ElaRadioButton *hxButton = new ElaRadioButton("横向",this);
    ElaRadioButton *zxButton = new ElaRadioButton("纵向",this);
    ElaRadioButton *dhdlButton = new ElaRadioButton("多行多列",this);
    m_hzjButtonGroup = new QButtonGroup(this);
    m_hzjButtonGroup->addButton(hxButton,0);
    m_hzjButtonGroup->addButton(zxButton,1);
    m_hzjButtonGroup->addButton(dhdlButton,2);
    connect(m_hzjButtonGroup, QOverload<QAbstractButton*, bool>::of(&QButtonGroup::buttonToggled), this,&T_SetParams::on_hzjButtonGroupToggled);
    dhdlButton->setChecked(true);
    hxButton->hide();
    zxButton->hide();
    dhdlButton->hide();
    hzjText->hide();

    QHBoxLayout *hLayout_10 = new QHBoxLayout();
    hLayout_10->addWidget(hzjText);
    hLayout_10->addStretch();
    hLayout_10->addWidget(hxButton);
    hLayout_10->addWidget(zxButton);
    hLayout_10->addWidget(dhdlButton);

    ElaText *xyzText = new ElaText("模组排列方式",15,this);
    hzjText->setWordWrap(false);
    m_xButton = new ElaRadioButton("X方向",this);
    m_yButton = new ElaRadioButton("Y方向",this);
    m_zButton = new ElaRadioButton("Z方向",this);
    m_xyzButtonGroup = new QButtonGroup(this);
    m_xyzButtonGroup->addButton(m_xButton,0);
    m_xyzButtonGroup->addButton(m_yButton,1);
    m_xyzButtonGroup->addButton(m_zButton,2);
    connect(m_xyzButtonGroup, QOverload<QAbstractButton*, bool>::of(&QButtonGroup::buttonToggled), this,&T_SetParams::on_xyzButtonGroupToggled);
    m_xButton->setChecked(true);
    m_zButton->hide();

    QHBoxLayout *hLayout_11 = new QHBoxLayout();
    hLayout_11->addWidget(xyzText);
    hLayout_11->addStretch();
    hLayout_11->addWidget(m_xButton);
    hLayout_11->addWidget(m_yButton);
    hLayout_11->addWidget(m_zButton);

    //创建行列设置和计算依据
    ElaText *rowText = new ElaText("行数或者列数",15,this);
    rowText->setWordWrap(false);
    m_setRowCol = new ElaLineEdit(this);
    connect(m_setRowCol,&ElaLineEdit::editingFinished,this,&T_SetParams::on_rowLeEditFinished);

    QHBoxLayout *hLayout_12 = new QHBoxLayout();
    hLayout_12->addWidget(rowText);
    hLayout_12->addStretch();
    hLayout_12->addWidget(m_setRowCol);

    ElaText *rowText1 = new ElaText("请选择行或者列",15,this);
    rowText1->setWordWrap(false);
    m_rowButton = new ElaRadioButton("行",this);
    m_colButton = new ElaRadioButton("列",this);
    m_rcButtonGroup = new QButtonGroup(this);
    m_rcButtonGroup->addButton(m_rowButton,0);
    m_rcButtonGroup->addButton(m_colButton,1);
    connect(m_rcButtonGroup,QOverload<QAbstractButton*, bool>::of(&QButtonGroup::buttonToggled),this,&T_SetParams::on_rcButtonGroupToggled);
    m_rowButton->setChecked(true);
    QHBoxLayout *hLayout_13 = new QHBoxLayout();
    hLayout_13->addWidget(rowText1);
    hLayout_13->addStretch();
    hLayout_13->addWidget(m_rowButton);
    hLayout_13->addWidget(m_colButton);

    //创建按钮
    ElaPushButton *calcNumBtn = new ElaPushButton("确认",this);
    connect(calcNumBtn,&ElaPushButton::clicked,this,&T_SetParams::on_calcNumBtnClicked);

    QHBoxLayout *hLayout_14 = new QHBoxLayout();
    hLayout_14->addStretch();
    hLayout_14->addWidget(calcNumBtn);
    hLayout_14->addStretch();

    m_blockInfoArea = new ElaScrollPageArea(this);
    m_blockInfoArea->setFixedSize(530,550);
    QVBoxLayout* vLayout = new QVBoxLayout(m_blockInfoArea);
    vLayout->addLayout(hLayout_0);
    vLayout->addSpacing(10);
    vLayout->addLayout(hLayout_1);
    vLayout->addSpacing(10);
    vLayout->addLayout(hLayout_2);
    vLayout->addSpacing(10);
    vLayout->addLayout(hLayout_3);
    vLayout->addSpacing(10);
    vLayout->addLayout(hLayout_4);
    vLayout->addSpacing(10);
    vLayout->addLayout(hLayout_5);
    vLayout->addSpacing(10);
    vLayout->addLayout(hLayout_6);
    vLayout->addSpacing(10);
    vLayout->addLayout(hLayout_7);
    vLayout->addSpacing(10);
    vLayout->addLayout(hLayout_8);
    vLayout->addLayout(hLayout_9);
    vLayout->addLayout(hLayout_10);
    vLayout->addLayout(hLayout_12);
    vLayout->addSpacing(10);
    vLayout->addLayout(hLayout_13);
    vLayout->addSpacing(10);
    vLayout->addLayout(hLayout_11);
    vLayout->addSpacing(10);
    vLayout->addLayout(hLayout_14);
    vLayout->addStretch();
}

void T_SetParams::createItem()
{
    //首先清空画布
    qInfo() << "清空画布";
    emit clearScene();
    double mainWidth;
    double mainHeight;
    if(m_main_is_swap) {
        mainWidth = m_totalHLe->text().toDouble();
        mainHeight = m_totalWLe->text().toDouble();
    } else {
        mainWidth = m_totalWLe->text().toDouble();
        mainHeight = m_totalHLe->text().toDouble();
    }

    qDebug() << "开始创建主体结构......";
    //添加主体
    cutomitem data;
    data.name = "主体箱";
    data.color = QColor(128, 128, 128);
    data.type = Main;
    data.rect = QRectF(0,0,mainWidth,mainHeight);
    emit addMainRect(data,MAINLEFT,MAINTOP,MAINRIGHT,MAINBOTTOM);

    //创建模板区域
    mainWidth = m_totalWLe->text().toDouble() - MAINRIGHT;
    mainHeight = m_totalHLe->text().toDouble() - MAINBOTTOM - MAINTOP;
    data.name = "模组区域";
    data.color = QColor(223,218,156);
    data.type = Module;
    data.rect = QRectF(0,0,mainWidth,mainHeight);
    emit addSubRect(data);

    qInfo() << "主体结构创建完成......";
    qDebug() << "开始创建电芯模组......";
    createBlockItem();
}

void T_SetParams::createOneGroup()
{
    //添加主体
    cutomitem data;
    data.name = "主体箱";
    data.color = QColor(128, 128, 128);
    data.type = Main;
    data.rect = QRectF(0,0,400.0,200.0);
    emit addMainRect1(data,0.0,0.0,0.0,0.0);

    //添加单模组
    double blockWidth;
    double blockHeight;
    switch (m_layout) {
    case LW:
    {
        blockWidth = g_blockInfo.length;
        blockHeight = g_blockInfo.width;
    }
    break;
    case LH:
    {
        blockWidth = g_blockInfo.length;
        blockHeight = g_blockInfo.height;
    }
    break;
    case HW:
    {
        blockWidth = g_blockInfo.height;
        blockHeight = g_blockInfo.width;
    }
    break;
    case WL:
    {
        blockWidth = g_blockInfo.width;
        blockHeight = g_blockInfo.length;
    }
    break;
    case WH:
    {
        blockWidth = g_blockInfo.width;
        blockHeight = g_blockInfo.height;
    }
    break;
    case HL:
    {
        blockWidth = g_blockInfo.height;
        blockHeight = g_blockInfo.length;
    }
    break;
    default:
        break;
    }

    data.name = "电芯串";
    data.color = QColor(54, 126, 127);
    data.type = Block;
    data.rect = QRectF(0,0,blockWidth,blockHeight);
    double space = BLOCKINTERVAL; //写死
    int num = m_blockSingNum;

    //创建block包
    g_item_group_names.clear();
    emit addBlockRect1(data,space,num,m_direction);

    //添加外框用于展示标注线
    QStringList list;
    QString tmp_name = QString("%1_%2").arg(data.name).arg(1);
    list.append(tmp_name);
    emit addOuterRect_paintLine1(list);

    T_PaintWidgetIns->ResizeView1();
}

void T_SetParams::createBlockItem()
{
    // if(m_blockSingNum == 0) {
    //     qCritical() << "创建失败......";
    //     return;
    // }

    m_list_groups.clear();
    //首先根据模组数量以及模组排布方式进行结构超限验证
    // if(!judgeGroup())
    // {
    //     // qCritical() << "创建电芯模组失败，请更换电芯或者重新选择参数尝试......";
    //     qWarning() << "范围超出参考图范围，请注意......";
    // }

    double blockWidth;
    double blockHeight;
    switch (m_layout) {
    case LW:
    {
        blockWidth = g_blockInfo.length;
        blockHeight = g_blockInfo.width;
    }
    break;
    case LH:
    {
        blockWidth = g_blockInfo.length;
        blockHeight = g_blockInfo.height;
    }
    break;
    case HW:
    {
        blockWidth = g_blockInfo.height;
        blockHeight = g_blockInfo.width;
    }
    break;
    case WL:
    {
        blockWidth = g_blockInfo.width;
        blockHeight = g_blockInfo.length;
    }
    break;
    case WH:
    {
        blockWidth = g_blockInfo.width;
        blockHeight = g_blockInfo.height;
    }
    break;
    case HL:
    {
        blockWidth = g_blockInfo.height;
        blockHeight = g_blockInfo.length;
    }
    break;
    default:
        break;
    }

    //添加电芯串
    cutomitem data;
    data.name = "电芯串";
    data.color = QColor(54, 126, 127);
    data.type = Block;
    data.rect = QRectF(0,0,blockWidth,blockHeight);
    double space = BLOCKINTERVAL; //写死
    // int num = /*m_blockSingleNumLe->text().toInt();*/m_blockSingNum;

    for(int i = 0; i < m_groupNum; i++) {
        //创建block包
        emit addBlockRect(data,space,m_one_row_or_col_num,m_direction);
        QString tmp_name = QString("%1_%2").arg(data.name).arg(i+1);
        m_list_groups.append(tmp_name);
    }

    //根据排列方式设置放置位置和间隔
    if(m_list_groups.count() < 2 && m_list_groups.count() > 0) {
        qInfo() << "电芯创建完成......";

        return;
    }

    QString firstItemName = m_list_groups.value(0); // 首行首元素
    QString prevRowFirst = firstItemName; // 上一行首元素
    QString currentRowFirst = firstItemName; // 当前行首元素
    int row = 1;
    int col = 1;
    for(int i = 1; i < m_list_groups.count(); i++){
        QStringList tmpList;
        // 每次只取相邻的两个元素：前一个(i-1)和当前(i)
        tmpList.append(m_list_groups.value(i-1));
        tmpList.append(m_list_groups.value(i));

        if(m_layout_group == HX) {
            emit cchildItemSpaceSignal(tmpList,MODELGROUPINTERVAL_H,0.0,"右侧对齐","顶部对齐");
        }
        else if(m_layout_group == ZX) {
            emit cchildItemSpaceSignal(tmpList,0.0,MODELGROUPINTERVAL_V,"左侧对齐","底部对齐");
        }
        else if(m_layout_group == DHDL) {
            //根据模组数量以及，最大支持行列数进行判断，一行一行的排,即先把列数排满
            // 判断是否换行（当前索引是新行的开始）
            bool isNewRowStart = ((i) % m_col_max == 0);
            if(isNewRowStart) {
                row += 1;
                col = m_col_max;
                // 1. 处理换行对齐：当前行首与上一行首垂直对齐
                QStringList verticalList;
                verticalList.append(prevRowFirst); // 上一行首元素
                verticalList.append(m_list_groups.value(i)); // 当前行首元素

                emit cchildItemSpaceSignal(verticalList, 0.0, MODELGROUPINTERVAL_V,"左侧对齐","底部对齐");

                // 2. 更新行首记录
                currentRowFirst = m_list_groups.value(i); // 设置新行首
                prevRowFirst = currentRowFirst; // 当前行变为上一行

                // 3. 处理新行内的第一个元素（不需要水平排列）
                continue; // 跳过后续水平排列处理
            }
            else {
                // 行内元素水平排列
                if(row <= 1) {
                    col = (i) % m_col_max + 1;
                } else {
                    col = m_col_max;
                }
                emit cchildItemSpaceSignal(tmpList,MODELGROUPINTERVAL_H,0.0,"右侧对齐","顶部对齐");
            }
        }
    }

    if(m_layout_group == DHDL) {
        double tmpSumWidth = (col * m_single_w) + ((col - 1) * MODELGROUPINTERVAL_H);
        double tmpSumHeight = (row * m_single_h) + ((row - 1) * MODELGROUPINTERVAL_V);
        g_resultInfo.pack_l_w_h = QString("%1*%2*%3mm").arg(tmpSumWidth).arg(tmpSumHeight).arg(m_sum_block_dh);
    }

    emit addOuterRect_paintLine(m_list_groups);
    qInfo() << "电芯创建完成......";

    T_PaintWidgetIns->ResizeView();
}

bool T_SetParams::judgeGroup()
{
    double mainWidth = m_totalWLe->text().toDouble() - MAINRIGHT;
    double mainHeight = m_totalHLe->text().toDouble() - MAINTOP - MAINBOTTOM;
    // int groupNum = m_groupNumLe->text().toInt();
    int singleNum = /*m_blockSingleNumLe->text().toInt();*/m_blockSingNum;
    int sumNum = /*m_blockNumLe->text().toInt();*/m_blockSumNum;    
    int groupNum = sumNum/singleNum;
    double tmpSumWidth = 0.0;
    double tmpSumHeight = 0.0;
    int row_col_max = 0;
    if(m_layout_group == HX) {
        tmpSumWidth = (groupNum * m_single_w) + ((groupNum - 1) * MODELGROUPINTERVAL_H);
        tmpSumHeight = m_single_h;
    } else if(m_layout_group == ZX) {
        tmpSumWidth = m_single_w;
        tmpSumHeight = (groupNum * m_single_h) + ((groupNum - 1) * MODELGROUPINTERVAL_V);
    } else if(m_layout_group == DHDL) {
        //计算横向最多摆多少个
        int hx_row_max = 0;
        int hx_col_max = 0;
        while(1) {
            double tmpWidth = (hx_col_max * m_single_w) + ((hx_col_max - 1) * MODELGROUPINTERVAL_H);
            if(tmpWidth >= mainWidth) {
                qInfo() << "最大能放列数：" << hx_col_max - 1;
                m_col_max = hx_col_max - 1;
                break;
            }
            hx_col_max += 1;
        }
        //计算横向最多摆多少列
        while(1) {
            double tmpHeight = (hx_row_max * m_single_h) + ((hx_row_max - 1) * MODELGROUPINTERVAL_V);
            if(tmpHeight >= mainHeight) {
                qInfo() << "最大能放行数：" << hx_row_max - 1;
                m_row_max = hx_row_max - 1;
                break;
            }
            hx_row_max += 1;
        }

        row_col_max = (hx_row_max - 1) * (hx_col_max - 1);
        tmpSumWidth = (m_col_max * m_single_w) + ((m_col_max - 1) * MODELGROUPINTERVAL_H);
        tmpSumHeight = (m_row_max * m_single_h) + ((m_row_max - 1) * MODELGROUPINTERVAL_V);
    }

    g_resultInfo.pack_l_w_h = QString("%1*%2*%3mm").arg(tmpSumWidth).arg(tmpSumHeight).arg(m_sum_block_dh);
    //判断是否结构超限
    if(tmpSumWidth < mainWidth && tmpSumHeight < mainHeight && m_layout_group != DHDL) {
        return true;
    } else if(groupNum <= row_col_max && m_layout_group == DHDL) {
        return true;
    } else {
        // qCritical() << "模组排列超限，此配置方案行不通。。。。。。";
        return false;
    }
}

void T_SetParams::calcCommon(double &blockSumWidth, double &blockSumHeight, int sum)
{
    double length = g_blockInfo.length;
    double width = g_blockInfo.width;
    double height = g_blockInfo.height;
    if(m_direction == 0){
        //水平放置
        switch (m_layout) {
        case LW:
        {
            blockSumWidth = (sum * length) + ((sum - 1) * BLOCKINTERVAL) + (g_duan_value_H * 2);
            blockSumHeight = width;
            m_sum_block_dh = height;
        }
        break;
        case LH:
        {
            blockSumWidth = (sum * length) + ((sum - 1) * BLOCKINTERVAL) + (g_duan_value_H * 2);
            blockSumHeight = height;
            m_sum_block_dh = width;
        }
        break;
        case HW:
        {
            blockSumWidth = (sum * height) + ((sum - 1) * BLOCKINTERVAL) + (g_duan_value_H * 2);
            blockSumHeight = width;
            m_sum_block_dh = length;
        }
        break;
        case WL:
        {
            blockSumWidth = (sum * width) + ((sum - 1) * BLOCKINTERVAL) + (g_duan_value_H * 2);
            blockSumHeight = length;
            m_sum_block_dh = height;
        }
        break;
        case WH:
        {
            blockSumWidth = (sum * width) + ((sum - 1) * BLOCKINTERVAL) + (g_duan_value_H * 2);
            blockSumHeight = height;
            m_sum_block_dh = length;
        }
        break;
        case HL:
        {
            blockSumWidth = (sum * height) + ((sum - 1) * BLOCKINTERVAL) + (g_duan_value_H * 2);
            blockSumHeight = length;
            m_sum_block_dh = width;
        }
        break;
        default:
            break;
        }
    }else if(m_direction == 1) {
        //垂直放置
        switch (m_layout) {
        case LW:
        {
            blockSumWidth = length;
            blockSumHeight = (sum * width) + ((sum - 1) * BLOCKINTERVAL) + (g_duan_value_V * 2);
            m_sum_block_dh = height;
        }
        break;
        case LH:
        {
            blockSumWidth = length;
            blockSumHeight = (sum * height) + ((sum - 1) * BLOCKINTERVAL) + (g_duan_value_V * 2);
            m_sum_block_dh = width;
        }
        break;
        case HW:
        {
            blockSumWidth = height;
            blockSumHeight = (sum * width) + ((sum - 1) * BLOCKINTERVAL) + (g_duan_value_V * 2);
            m_sum_block_dh = length;
        }
        break;
        case WL:
        {
            blockSumWidth = width;
            blockSumHeight = (sum * length) + ((sum - 1) * BLOCKINTERVAL) + (g_duan_value_V * 2);
            m_sum_block_dh = height;
        }
        break;
        case WH:
        {
            blockSumWidth = width;
            blockSumHeight = (sum * height) + ((sum - 1) * BLOCKINTERVAL) + (g_duan_value_V * 2);
            m_sum_block_dh = length;
        }
        break;
        case HL:
        {
            blockSumWidth = height;
            blockSumHeight = (sum * length) + ((sum - 1) * BLOCKINTERVAL) + (g_duan_value_V * 2);
            m_sum_block_dh = width;
        }
        break;
        default:
            break;
        }
    } else if(m_direction == 2) {
        //堆叠放置
        switch (m_layout) {
        case LW:
        {
            blockSumWidth = length /*+ (g_duan_value_H * 2)*/;
            blockSumHeight = width;
            m_sum_block_dh = (sum * height) + ((sum - 1) * BLOCKINTERVAL);
        }
        break;
        case WL:
        {
            blockSumWidth = width;
            blockSumHeight = length /*+ (g_duan_value_V * 2)*/;
            m_sum_block_dh = (sum * height) + ((sum - 1) * BLOCKINTERVAL);
        }
        break;
        default:
            break;
        }
    }
}

void T_SetParams::calcModelGroupCount()
{
    //首先判断串数是否为偶数，不是的话则加1
    int cCount = /*m_cLe->text().toInt()*/m_c_num;
    if(cCount % 2 != 0) {
        cCount += 1;
        // m_cLe->setText(QString::number(cCount));
        m_c_num = cCount;
    }
    //计算最小模组数量
    qDebug() << "开始计算模组最小数量......";
    while(1) {
        if(m_splitInt > cCount) {
            qCritical() << "未找到合适点单模组电芯数，请调整电压或者容量";
            m_is_allow_create = false;
            return;
        }
        else if(cCount % m_splitInt != 0) {
            m_splitInt += 1;
        } else {
            int ret = cCount / m_splitInt;
            int tmpret = ret % m_b_num;
            if((ret * m_b_num) > m_pack_count_max || (tmpret != 0)) {
                m_splitInt += 1;
            } else {
                qInfo() << "单模组电芯数量为：" << ret << " 模组最小数量为：" << m_splitInt;
                // m_blockSingleNumLe->setText(QString::number(ret));
                // m_groupNumLe->setText(QString::number(m_splitInt));
                m_blockSingNum = ret * m_b_num;
                m_onePNum = ret;
                m_groupNum = m_splitInt;
                break;
            }
        }
    }

    qDebug() << "开始矫正单模组电芯数量以及模组最小数量......";
    //计算单模组是否超结构尺寸
    double blockSumWidth = 0.0;   //总长
    double blockSumHeight = 0.0;  //总宽
    int block_single_sum = /*m_blockSingleNumLe->text().toInt();*/m_blockSingNum;

    //计算单模组总长度与总宽度
    calcCommon(blockSumWidth,blockSumHeight,block_single_sum);
    //比对结果
    qDebug() << "开始对比结构尺寸是否超限......";
    int ret = judgeSplit(blockSumWidth,blockSumHeight);
    if(!ret) {
        qWarning() << "重新计算验证......";
        //重新计算验证
        m_splitInt += 1;
        calcModelGroupCount();
    } else {
        //赋值单个模块的大小
        m_single_w = blockSumWidth;
        m_single_h = blockSumHeight;
    }
}

bool T_SetParams::judgeSplit(double blockSumWidth, double blockSumHeight)
{
    double mainWidth = m_totalWLe->text().toDouble();
    double mainHeight = m_totalHLe->text().toDouble();
    double mainHD = m_totalHDLe->text().toDouble();

    if(blockSumWidth < mainWidth && blockSumHeight < mainHeight && m_sum_block_dh < mainHD) {
        int nowBlockNum = /*m_blockSingleNumLe->text().toInt();*/m_blockSingNum;
        int nowGroupNum = /*m_cLe->text().toInt()*/m_c_num / nowBlockNum;
        qInfo() << "矫正完成，单模组电芯数量为：" << nowBlockNum << " 模组最小数量为：" << nowGroupNum;
        m_groupNum = nowGroupNum;
        return true;
    } else {
        qWarning() << "宽度、高度、或者厚度已经超出范围，需要分割多个......正在重新计算模组数量......";
        return false;
    }
}

void T_SetParams::calc()
{
    if(!m_is_allow_create) {
        ElaMessageBar::error(ElaMessageBarType::BottomRight,"警告","已改变参数配置，请点击计算数量按钮重新计算模组数量",3000,this->parentWidget());
        return;
    }

    double sumVol = m_blockVolValueLe->text().toDouble();
    double sumkWh = m_blockAhValueLe->text().toDouble();
    //计算容量
    double sumAh = (sumkWh * 1000) / sumVol;
    qDebug() << "计算容量为：" << sumAh << " Ah";

    //计算串数
    int num = 0;
    double quotient = 0.0;
    quotient = sumVol / g_blockInfo.voltage;
    // 使用浮点数比较代替取模运算
    if (std::abs(quotient - std::floor(quotient)) > std::numeric_limits<double>::epsilon()) {
        num = static_cast<int>(std::ceil(quotient));
    } else {
        num = static_cast<int>(quotient);
    }
    // if(num % 2 != 0) {
    //     num += 1;
    // }
    m_c_num = num;
    qDebug() << "串数为：" << m_c_num;

    //计算并数
    num = 0;
    quotient = 0.0;
    quotient = sumAh / g_blockInfo.kWh;
    // 使用浮点数比较代替取模运算
    if (std::abs(quotient - std::floor(quotient)) > std::numeric_limits<double>::epsilon()) {
        num = static_cast<int>(std::ceil(quotient));
    } else {
        num = static_cast<int>(quotient);
    }
    m_b_num = num;
    qDebug() << "并数为：" << m_b_num;

    m_blockSumNum = num * m_c_num;
    qDebug() << "电芯总数为：" << m_blockSumNum;

    //计算1P的电芯数量
    int onePNum = m_c_num / m_b_num;
    qDebug() << "1并电芯串数：" << onePNum;

    //根据行或者列计算一行或者一列有多少个电芯
    if(m_row_or_col == ROW) {
        m_groupNum = m_set_row_max;
        m_one_row_or_col_num = m_blockSumNum / m_set_row_max;
        int one_s = m_one_row_or_col_num / m_b_num;
        qDebug() << "每行电芯数量为：" << m_one_row_or_col_num;
        qDebug() << "每行每并电芯串数为：" << one_s;

        //计算每个的长宽高
        double blockSumWidth = 0.0;
        double blockSumHeight = 0.0;
        calcCommon(blockSumWidth,blockSumHeight,m_one_row_or_col_num);

        m_single_w = blockSumWidth;
        m_single_h = blockSumHeight;
        auto placeholder = QString("每行尺寸为：%1*%2*%3 mm")
                               .arg(QString::number(m_single_w, 'f', 2))
                               .arg(QString::number(m_single_h, 'f', 2))
                               .arg(QString::number(m_sum_block_dh, 'f', 2));
        qDebug() << placeholder;

        double tmpSumWidth = m_single_w;
        double tmpSumHeight = m_single_h * m_set_row_max + (m_set_row_max - 1) * MODELGROUPINTERVAL_V;
        g_resultInfo.pack_l_w_h = QString("%1*%2*%3mm").arg(tmpSumWidth).arg(tmpSumHeight).arg(m_sum_block_dh);

    } else if(m_row_or_col == COL) {
        m_groupNum = m_set_col_max;
        m_one_row_or_col_num = m_blockSumNum / m_set_col_max;
        int one_s = m_one_row_or_col_num / m_b_num;
        qDebug() << "每列电芯数量为：" << m_one_row_or_col_num;
        qDebug() << "每行每并电芯串数为：" << one_s;

        //计算每个的长宽高
        double blockSumWidth = 0.0;
        double blockSumHeight = 0.0;
        calcCommon(blockSumWidth,blockSumHeight,m_one_row_or_col_num);

        m_single_w = blockSumWidth;
        m_single_h = blockSumHeight;
        auto placeholder = QString("每列尺寸为：%1*%2*%3 mm")
                               .arg(QString::number(m_single_w, 'f', 2))
                               .arg(QString::number(m_single_h, 'f', 2))
                               .arg(QString::number(m_sum_block_dh, 'f', 2));

        double tmpSumWidth = m_single_w * m_set_col_max + (m_set_col_max - 1) * MODELGROUPINTERVAL_H;
        double tmpSumHeight = m_single_h;
        g_resultInfo.pack_l_w_h = QString("%1*%2*%3mm").arg(tmpSumWidth).arg(tmpSumHeight).arg(m_sum_block_dh);
    }

    //输出结果
    calcResult();

    //刷新数据
    T_PackInfoIns->flushPackInfo();
}

void T_SetParams::calcResult()
{
    int tmpSumWeight = m_blockSumNum * g_blockInfo.weight / 1000;
    double tmpVol = m_blockVolValueLe->text().toDouble();
    double minVol = m_c_num *g_blockInfo.outStopVol;
    double maxVol = m_c_num *g_blockInfo.inStopVol;
    double sumkWh = /*m_blockAhValueLe->text().toDouble();*/m_c_num * m_b_num * g_blockInfo.voltage * g_blockInfo.kWh / 1000;
    double continueOutC = g_blockInfo.outContinue.left(g_blockInfo.outContinue.size() - 1).toDouble();
    double continueOutKw = sumkWh * continueOutC;
    double continueInC = g_blockInfo.inContinue.left(g_blockInfo.inContinue.size() - 1).toDouble();
    double continueInKw = sumkWh * continueInC;
    double continueTenC = g_blockInfo.out10.left(g_blockInfo.out10.size() - 1).toDouble();
    double continueTenKw = sumkWh * continueTenC;

    QString result_1 = "";
    if(tmpVol >= minVol && tmpVol <= maxVol)
    {
        result_1 = "电压范围没问题";
    } else {
        result_1 = "电压范围不合理";
    }
    QString result_2 = QString("尺寸为：%1").arg(g_resultInfo.pack_l_w_h);
    g_resultInfo.result = QString("该结果仅供初步评估，%1，%2，其他信息请参考评估表").arg(result_1).arg(result_2);
    g_resultInfo.standerdVol = QString("%1V").arg(QString::number(tmpVol,'f',2));
    g_resultInfo.voltageRange = QString("%1-%2V").arg(QString::number(minVol,'f',2)).arg(QString::number(maxVol,'f',2));
    g_resultInfo.sumkWh = QString("%1kWh").arg(QString::number(sumkWh,'f',2));
    g_resultInfo.continueOuterKW = QString("%1kw").arg(QString::number(continueOutKw,'f',2));
    g_resultInfo.outer_10_kw = QString("%1kw").arg(QString::number(continueTenKw,'f',2));
    g_resultInfo.continueInterKW = QString("%1kw").arg(QString::number(continueInKw,'f',2));
    g_resultInfo.c_b_way = QString("%1P%2S").arg(m_b_num).arg(m_c_num);
    g_resultInfo.sumWeight = QString("%1kg").arg(tmpSumWeight);

    qInfo() << "结果=> " << g_resultInfo.result;
}

void T_SetParams::importExcel(const QString &excel_path)
{
    m_combobox->clear();
    T_ExcelIns->ReadExcel(excel_path);
    for(const auto &key : g_block_map.keys()) {
        m_combobox->addItem(key);
    }
    if(m_combobox->count() > 0) {
        m_is_import_excel = true;
    } else {
        ElaMessageBar::error(ElaMessageBarType::BottomRight,"错误","导入参数表失败",3000,this->parentWidget());
        m_is_import_excel = false;
    }
}

void T_SetParams::on_currentTextChanged(const QString &text)
{
    g_blockInfo = g_block_map[text];
    //刷新电芯参数显示
    emit flushBlockInfo();

    double tmplength = g_blockInfo.length;
    double tmpwidth = g_blockInfo.width;
    double tmpheight = g_blockInfo.height;
    if(g_blockInfo.jgtype.compare("软包") == 0) {
        m_duan_value_H = RBDUAN;
        m_duan_value_V = RBDUAN;
        g_duan_value_H = 0.0;
        g_duan_value_V = m_duan_value_V;
        m_pack_count_max = SOFTPACKCOUNTMAX;
        // m_lwButton->show();
        // m_lhButton->show();
        // m_hwButton->hide();
        // m_hlButton->show();
        // m_whButton->hide();
        // m_wlButton->show();
        g_blockInfo.length = tmplength;
        g_blockInfo.width = tmpwidth;
        g_blockInfo.height = tmpheight;

        m_xButton->show();
        m_yButton->show();
        m_xButton->setChecked(true);

        m_rowButton->show();
        m_colButton->show();
        m_rowButton->setChecked(true);
    } else {
        m_duan_value_H = FKDUAN;
        m_duan_value_V = FKDUAN;
        g_duan_value_H = 0.0;
        g_duan_value_V = m_duan_value_V;
        m_pack_count_max = SQUREPACKCOUNTMAX;
        // m_lwButton->hide();
        // m_lhButton->show();
        // m_hwButton->hide();
        // m_hlButton->show();
        // m_whButton->hide();
        // m_wlButton->hide();
        g_blockInfo.length = tmplength;
        g_blockInfo.width = tmpheight;
        g_blockInfo.height = tmpwidth;

        //电芯只考虑从左往右排列
        m_xButton->hide();
        m_yButton->show();
        m_yButton->setChecked(true);
        //只能设置行数
        m_rowButton->show();
        m_colButton->hide();
        m_rowButton->setChecked(true);
    }

    if(!m_blockVolValueLe->text().isEmpty()){
        emit m_blockVolValueLe->editingFinished();
    }
    if(!m_blockAhValueLe->text().isEmpty()){
        emit m_blockAhValueLe->editingFinished();
    }

    m_xButton->hide();
    m_yButton->show();
    m_yButton->setChecked(true);

    m_is_allow_create = false;
}

void T_SetParams::on_importExcelBtnClicked()
{
    QString excel_path = QFileDialog::getOpenFileName(nullptr,tr("Open File"),
                                                      "/home",
                                                      tr("Excel File (*.xlsx)"));

    importExcel(excel_path);
}

void T_SetParams::on_volLeEditFinished()
{
    if(!m_is_import_excel){
        ElaMessageBar::error(ElaMessageBarType::BottomRight,"警告","请先导入电芯参数表",3000,this->parentWidget());
        return;
    }    

    double sum = m_blockVolValueLe->text().toDouble();
    int num;
    double quotient = sum / g_blockInfo.voltage;
    // 使用浮点数比较代替取模运算
    if (std::abs(quotient - std::floor(quotient)) > std::numeric_limits<double>::epsilon()) {
        num = static_cast<int>(std::ceil(quotient));
    } else {
        num = static_cast<int>(quotient);
    }
    if(num % 2 != 0) {
        num += 1;
    }
    m_c_num = num;
    m_blockSumNum = num * m_b_num;
    m_is_allow_create = false;
}

void T_SetParams::on_ahLeEditFinished()
{
    if(!m_is_import_excel){
        ElaMessageBar::error(ElaMessageBarType::BottomRight,"警告","请先导入电芯参数表",3000,this->parentWidget());
        return;
    }

    //电芯容量
    double sum = (m_blockAhValueLe->text().toDouble() * 1000) / m_blockVolValueLe->text().toDouble();
    // double sum = m_blockAhValueLe->text().toDouble();
    int num;
    double quotient = sum / g_blockInfo.kWh;

    // 使用浮点数比较代替取模运算
    if (std::abs(quotient - std::floor(quotient)) > std::numeric_limits<double>::epsilon()) {
        num = static_cast<int>(std::ceil(quotient));
    } else {
        num = static_cast<int>(quotient);
    }
    m_b_num = num;
    m_blockSumNum = num * m_c_num;
    m_is_allow_create = false;
}

void T_SetParams::on_rowLeEditFinished()
{
    m_set_row_max = m_setRowCol->text().toInt();
    m_set_col_max = m_setRowCol->text().toInt();
    m_is_allow_create = false;
}

void T_SetParams::on_hvddButtonGroupToggled(QAbstractButton *button, bool isToggled)
{
    if (isToggled)
    {
        m_is_allow_create = false;
        int id = m_hvddButtonGroup->id(button);
        if(id == 0){
            m_direction = 0;
            g_duan_value_H = m_duan_value_H;
            g_duan_value_V = 0.0;
        } else if(id == 1) {
            m_direction = 1;
            g_duan_value_H = 0.0;
            g_duan_value_V = m_duan_value_V;
        } else if(id == 2) {
            m_direction = 2;
            g_duan_value_H = 0.0;
            g_duan_value_V = 0.0;
        }
    }
}

void T_SetParams::on_lwhlButtonGroupToggled(QAbstractButton *button, bool isToggled)
{
    if (isToggled)
    {
        m_is_allow_create = false;
        int id = m_lwhlButtonGroup->id(button);
        if(id == 0){
            m_layout = LW;
            // m_hButton->hide();
            // m_vButton->hide();
            // m_ddButton->show();
            m_ddButton->setChecked(true);
        } else if(id == 1) {
            m_layout = LH;
            // m_hButton->hide();
            // m_vButton->show();
            // m_ddButton->hide();
            m_vButton->setChecked(true);
        } else if(id == 2) {
            m_layout = HW;
            // m_hButton->hide();
            // m_vButton->hide();
            // m_ddButton->hide();
        } else if(id == 3) {
            m_layout = WL;
            // m_hButton->hide();
            // m_vButton->hide();
            // m_ddButton->show();
            m_ddButton->setChecked(true);
        } else if(id == 4) {
            m_layout = WH;
            // m_hButton->hide();
            // m_vButton->hide();
            // m_ddButton->hide();
        } else if(id == 5) {
            m_layout = HL;
            // m_hButton->show();
            // m_vButton->hide();
            // m_ddButton->hide();
            m_hButton->setChecked(true);
        }
    }
}

void T_SetParams::on_hzjButtonGroupToggled(QAbstractButton *button, bool isToggled)
{
    if (isToggled)
    {
        int id = m_hzjButtonGroup->id(button);
        if(id == 0){
            m_layout_group = HX;
        } else if(id == 1) {
            m_layout_group = ZX;
        } else if(id == 2) {
            m_layout_group = DHDL;
        }
    }
}

void T_SetParams::on_xyzButtonGroupToggled(QAbstractButton *button, bool isToggled)
{
    if (isToggled)
    {
        int id = m_xyzButtonGroup->id(button);
        if(id == 0){
            //X方向
            m_lhButton->setChecked(true);
        } else if(id == 1) {
            //Y方向
            m_hlButton->setChecked(true);
        } else if(id == 2) {
            //Z方向
        }
    }
}

void T_SetParams::on_rcButtonGroupToggled(QAbstractButton *button, bool isToggled)
{
    if (isToggled)
    {
        int id = m_rcButtonGroup->id(button);
        if(id == 0){            
            m_row_or_col = ROW;

            m_xButton->hide();
            m_yButton->show();
            m_yButton->setChecked(true);

            m_layout_group = ZX;
        } else if(id == 1) {
            //列
            m_row_or_col = COL;
            m_xButton->show();
            m_yButton->hide();
            m_xButton->setChecked(true);

            m_layout_group = HX;
        }

        m_is_allow_create = false;
    }
}

void T_SetParams::on_calcNumBtnClicked()
{
    if(/*m_cLe->text().isEmpty() || m_bLe->text().isEmpty()*/m_c_num <= 0 ||m_b_num <= 0) {
        ElaMessageBar::error(ElaMessageBarType::BottomRight,"错误","请先输入总电压和总电量得到串数和并数",3000,this->parentWidget());
        return;
    }
    if(m_totalWLe->text().isEmpty() || m_totalHLe->text().isEmpty() || m_totalHDLe->text().isEmpty()) {
        ElaMessageBar::error(ElaMessageBarType::BottomRight,"错误","请先输入结构的长、宽、厚度",3000,this->parentWidget());
        return;
    }

    if(m_row_or_col == ROW && m_set_row_max < 1) {
        ElaMessageBar::error(ElaMessageBarType::BottomRight,"错误","请先输入行数",3000,this->parentWidget());
        return;
    }

    if(m_row_or_col == COL && m_set_col_max < 1) {
        ElaMessageBar::error(ElaMessageBarType::BottomRight,"错误","请先输入列数",3000,this->parentWidget());
        return;
    }

    m_is_allow_create = true;
    m_splitInt = 1;
    // calcModelGroupCount();
    calc();

    emit flushPackInfo(/*m_one_row_or_col_num*/m_c_num,m_blockSumNum,m_groupNum);

    if(m_is_allow_create) {
        createItem();
        //创建一个单模组就行
        // createOneGroup();
    } else {
        ElaMessageBar::error(ElaMessageBarType::BottomRight,"警告","已改变参数配置，请点击计算数量按钮重新计算模组数量",3000,this->parentWidget());
        return;
    }
}


